<template>
	<view>
		<z-nav-bar title="兑换积分">
			<template #right>
				<navigator url="/pages/student/recharge-list" hover-class="none">
					<view style="color: #00ab64">兑换列表</view>
				</navigator>
			</template>
		</z-nav-bar>
		<view class="content">
			<view class="title">需要兑换的金额</view>
			<view class="price">
				<view>￥</view>
				<view>
					<input
						v-model="amount"
						type="number"
						placeholder="请输入金额"
						placeholder-class="placeholderStyle"
					/>
				</view>
			</view>
			<view class="title">选择要兑换积分的金额</view>
			<view class="option">
				<view :class="amount == 1 ? ['item', 'active'] : ['item']" @click="chose_price(1)">
					<view class="text">
						1
						<text>元</text>
					</view>
				</view>
				<view :class="amount == 3 ? ['item', 'active'] : ['item']" @click="chose_price(3)">
					<view class="text">
						3
						<text>元</text>
					</view>
				</view>
				<view :class="amount == 8 ? ['item', 'active'] : ['item']" @click="chose_price(8)">
					<view class="text">
						8
						<text>元</text>
					</view>
				</view>
			</view>
		</view>
		<!-- #ifndef MP-WEIXIN -->
		<view class="pay">
			<view class="title">充值方式</view>
			<view class="type" @click="payType = 'wechat_app'">
				<view class="left">
					<image :src="`${setting.sImgUrl}/icon_WeChat@2x.png`"></image>
					<view>微信充值</view>
				</view>
				<image
					:src="`${setting.oss_pub_domain}/app-img/icon/student_select${
						payType == 'wechat_app' ? 'ed' : ''
					}.png`"
					class="icon-size-32 uni-mr-16"
				></image>
			</view>
			<view class="type" @click="payType = 'alipay_app'">
				<view class="left">
					<image :src="`${setting.sImgUrl}/icon_Alipay@2x.png`"></image>
					<view>支付宝充值</view>
				</view>
				<image
					:src="`${setting.oss_pub_domain}/app-img/icon/student_select${
						payType == 'alipay_app' ? 'ed' : ''
					}.png`"
					class="icon-size-32 uni-mr-16"
				></image>
			</view>
			<view v-if="platform === 'ios'" class="type" @click="payType = 'apple_pay'">
				<view class="left">
					<image :src="`${setting.oss_pub_domain}/app-img/icon/apple.png`"></image>
					<view>苹果充值</view>
				</view>
				<image
					:src="`${setting.oss_pub_domain}/app-img/icon/student_select${
						payType == 'apple_pay' ? 'ed' : ''
					}.png`"
					class="icon-size-32 uni-mr-16"
				></image>
			</view>
		</view>
		<!-- #endif -->
		<view class="rule">
			<view class="title">规则</view>
			<view class="detail">
				<view>1. 金额与积分的兑换比例为1: 100</view>
				<view>2. 积分可用于APP内服务消费及兑换</view>
				<view>3. 最终解释权归降杆所有;</view>
			</view>
		</view>
		<view class="btn" @click="topUp">
			<text>确认充值</text>
		</view>
	</view>
</template>

<script>
import { getPayInfo } from '@/api/my.js';
import { checkPayWxStatus, bindWxPay, checkApplePay } from '@/api/integral.js';
export default {
	data() {
		return {
			amount: 1,
			amountList: [1, 3, 8],
			payType: 'wechat_app',
			iapChannel: '',
			platform: '',
			productid: '',
			IapTransactionState: {
				purchasing: '0',
				purchased: '1',
				failed: '2',
				restored: '3',
				deferred: '4'
			}
		};
	},
	mounted() {
		// #ifdef MP-WEIXIN
		checkPayWxStatus().then((res) => {
			if (!res) {
				wx.login({
					success: (res) => {
						bindWxPay({ code: res.code });
					}
				});
			}
		});
		// #endif
		this.platform = uni.getSystemInfoSync().platform;
		if (this.platform === 'ios') {
			uni.getProvider({
				service: 'payment',
				success: (res) => {
					this.iapChannel = res.providers.find((channel) => channel.id === 'appleiap');
					this.iapChannel.requestProduct(this.amountList.map((item) => `buy.score.${item}`));
					this.iapChannel.restoreCompletedTransactions(
						{
							manualFinishTransaction: true,
							username: ''
						},
						(checkData) => {
							checkData.forEach((transaction) => {
								switch (transaction.transactionState) {
									case this.IapTransactionState.purchased:
										this.checkApplePayOrder(transaction);
										break;
									case this.IapTransactionState.failed:
										this.iapChannel.finishTransaction(transaction);
										break;
									default:
										break;
								}
							});
						}
					);
				}
			});
		}
	},
	methods: {
		chose_price(amount) {
			this.amount = amount;
		},
		topUp() {
			const payTypeObj = {
				wechat_app: 'wxpay',
				wechat_mini: 'wxpay',
				alipay_app: 'alipay'
			};
			if (this.payType === 'apple_pay') return this.applePayment();
			if (!this.amount) return this.tools.alert('请输入或选择充值金额');
			const params = {
				amount: this.amount
			};
			// #ifdef APP-PLUS
			params.payType = this.payType;
			// #endif
			// #ifdef MP-WEIXIN
			params.payType = 'wechat_mini';
			// #endif
			getPayInfo(params).then((res) => {
				// #ifdef MP-WEIXIN
				res = JSON.parse(res);
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: res.timeStamp,
					nonceStr: res.nonceStr,
					package: res.package,
					signType: res.signType,
					paySign: res.paySign,
					success: (res) => {
						this.tools.alert('支付成功');
						uni.navigateBack();
					},
					fail: (err) => {
						this.tools.alert('支付失败' + JSON.stringify(err));
					}
				});
				// #endif
				// #ifdef APP-PLUS
				uni.requestPayment({
					provider: payTypeObj[this.payType],
					orderInfo: this.payType == 'wechat_app' ? JSON.parse(res) : res,
					success: (res) => {
						this.tools.alert('支付成功');
						uni.navigateBack();
					},
					fail: (e) => {
						console.log(e);
					}
				});
				// #endif
			});
		},
		applePayment() {
			uni.showLoading({
				title: '支付中,请稍后...'
			});
			uni.requestPayment({
				provider: 'appleiap',
				orderInfo: {
					productid: `buy.score.${this.amount}`,
					manualFinishTransaction: true
				},
				success: (transaction) => {
					uni.showLoading({
						title: '支付成功,检查订单中...'
					});
					this.checkApplePayOrder(transaction, 1);
				},
				fail: (error) => {
					this.tools.alert('支付失败');
					uni.hideLoading();
				}
			});
		},
		checkApplePayOrder(transaction, alert) {
			checkApplePay({
				productId: transaction.payment.productid,
				receiptData: transaction.transactionReceipt
			})
				.then((res) => {
					if (res) this.iapChannel.finishTransaction(transaction);
					uni.hideLoading();
					setTimeout(() => {
						if (alert) this.tools.alert('支付成功');
						setTimeout(() => {
							uni.navigateBack();
						}, 1000);
					});
				})
				.catch((err) => {
					uni.hideLoading();
					this.tools.alert('校验失败');
				});
		}
	}
};
</script>

<style>
@import './css/recharge.css';
</style>
